package com.tmanager.persistence.tx;

import static com.google.inject.matcher.Matchers.annotatedWith;
import static com.google.inject.matcher.Matchers.any;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.AbstractModule;
import com.google.inject.Provides;

public class TxModule extends AbstractModule {
	private static final Logger log = LoggerFactory.getLogger(TxModule.class);

	@Override
	protected void configure() {
		TransactionalInterceptor interceptor = new TransactionalInterceptor();
		requestInjection(interceptor);
		bindInterceptor(any(), annotatedWith(Transactional.class), interceptor);
		bind(EntityManager.class).toProvider(EntityManagerProvider.class);
	}

	@Provides
	EntityManagerFactory provideEntityManagerFactory() throws Exception {
		try {
			return Persistence.createEntityManagerFactory("JPAUnit");
		} catch (Exception e) {
			log.error("Error while creating EntityManagerFactory", e);
			throw e;
		}
	}

}
